//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package upgrade

import (
	"context"
	"math"
	"time"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/chat_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_dao"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

type UpToVer26 struct{}

func (up *UpToVer26) Exec(ctx context.Context) error {
	prjList, err := project_dao.ProjectInfoDao.ListAll(ctx, 0, math.MaxInt64)
	if err != nil {
		return err
	}
	for _, prj := range prjList {
		err = up.fixProject(ctx, prj)
		if err != nil {
			return err
		}
	}
	return dao.VersionDao.Set(ctx, dao.VERSION_KEY_SCHEMA, 26)
}

func (up *UpToVer26) fixProject(ctx context.Context, projectItem *project_dao.ProjectInfoDbItem) error {
	if projectItem.DefaultChatGroupId != "" {
		return nil
	}

	memberItemList, err := project_dao.MemberInfoDao.ListMember(ctx, projectItem.ProjectId)
	if err != nil {
		return err
	}

	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return err
	}
	defer dao.EndSession(dbSess)

	_, err = dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		if projectItem.DefaultChatGroupId == "" {
			projectItem.DefaultChatGroupId = uuid.NewString()
			err = chat_dao.GroupDao.Insert(sessCtx, &chat_dao.ChatGroupInfoDbItem{
				ChatGroupId: projectItem.DefaultChatGroupId,
				ProjectId:   projectItem.ProjectId,
				Title:       "全体成员",
				System:      true,
				OwnerUserId: projectItem.OwnerUserId,
				LastMsgId:   "",
				CreateTime:  nowTime,
			})
			if err != nil {
				return nil, err
			}
		}

		err = project_dao.ProjectInfoDao.UpdateProject(sessCtx, projectItem)
		if err != nil {
			return nil, err
		}

		for _, memberItem := range memberItemList {
			err = chat_dao.GroupMemberDao.Insert(ctx, &chat_dao.MemberDbItem{
				ProjectId:   projectItem.ProjectId,
				ChatGroupId: projectItem.DefaultChatGroupId,
				UserId:      memberItem.MemberUserId,
				UnreadCount: 0,
				LastMsgTime: nowTime,
				JoinTime:    nowTime,
			})
			if err != nil {
				return nil, err
			}
		}
		return nil, nil
	})
	return err
}
